<?php
/**
 * Created by PhpStorm.
 * User: Xwen
 * Date: 2018/12/16
 * Time: 15:37
 *
 *          ┌─┐       ┌─┐
 *       ┌──┘ ┴───────┘ ┴──┐
 *       │                 │
 *       │       ───       │
 *       │  ─┬┘       └┬─  │
 *       │                 │
 *       │       ─┴─       │
 *       │                 │
 *       └───┐         ┌───┘
 *           │         │
 *           │         │
 *           │         │
 *           │         └──────────────┐
 *           │                        │
 *           │                        ├─┐
 *           │                        ┌─┘
 *           │                        │
 *           └─┐  ┐  ┌───────┬──┐  ┌──┘
 *             │ ─┤ ─┤       │ ─┤ ─┤
 *             └──┴──┘       └──┴──┘
 *                 神兽保佑
 *                 代码无BUG!
 *"The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.”- Seymour Cray
 */

namespace app\admin\logic;

use think\Db;
use think\Request;
use app\admin\validate\User as UserValidate;
use think\Session;

class User
{
    protected $request;
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function infos($pageNumber, $pageSize, $name = NULL, $email = NULL){
        $where[] = ['is_delete', '=', 0];
        if($name != NULL){
            $where[] = ['username', 'LIKE', '%'.$name.'%'];
        }
        if($email != NULL){
            $where[] = ['email', 'LIKE', '%'.$email.'%'];
        }
        $data = model("User")->getPage($where, $pageNumber, $pageSize);
        $count = model("User")->getCount($where);
        return [
            'total'      =>         $count,
            'rows'       =>         $data,
        ];
    }
    public function add($data){
        $validate = new UserValidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            exception($validate->getError());
        }
        $adminName = (new Session())->get('USER_INFO.userName');
        $info['creator'] = $adminName;
        $info['updater'] = $adminName;
        $info['create_time'] = time();
        $info['update_time'] = time();
        $role_ids = $data['role_ids'];
        unset($data['role_ids']);

        $data['password'] = md5($data['password']);
        $data = array_merge($data, $info);
        Db::startTrans();
        try {
            $userId =  model("User")->insertGetId($data);
            if(!empty($role_ids)){
                $urData = array();
                foreach ($role_ids as $k => $v){
                    $urData[$k]['user_id'] = $userId;
                    $urData[$k]['role_id'] = $v;
                    $urData[$k] = array_merge($urData[$k], $info);
                }
                model('UserRole')->insertAll($urData);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }

    }
    public function edit($data){
        $validate = new UserValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            exception($validate->getError());
        }
        $adminName = (new Session())->get('USER_INFO.userName');
        if(isset($data['password']) && empty($data['password'])){
            unset($data['password']);
        }else{
            $data['password'] = md5($data['password']);
        }
        $data['updater'] = $adminName;
        $data['update_time'] = time();
        $id = $data['id'];
        $role_ids = $data['role_ids'];
        unset($data['id']);
        unset($data['role_ids']);
        Db::startTrans();
        try {
            $userWhere[] = ['is_delete', 'eq', 0];
            $userWhere[] = ['id', 'eq', $id];
            model("User")->where($userWhere)->update($data);

            $infos['updater'] = $adminName;
            $infos['update_time'] = time();
            $info['creator'] = $adminName;
            $info['create_time'] = time();
            $where[] = ['is_delete', 'eq', 0];
            $where[] = ['user_id', 'eq', $id];
            $rData = [
                'is_delete'     =>  1
            ];
            if(!empty($role_ids)){
                $user_role = model('UserRole')->where('is_delete', 'eq', 0)
                    ->where('user_id', 'eq', $id)->field('role_id')->select()->toArray();
                $user_role = array_column($user_role, 'role_id');
                // 提交的数据相对之前数据的差集（需禁用项）
                $user_role_delete = array_diff($user_role, $role_ids);
                model('UserRole')->where($where)->whereIn('role_id', $user_role_delete)->update(array_merge($infos, $rData));
                // 之前数据相对提交的数据的差集（需添加项）
                $user_role_add = array_diff($role_ids, $user_role);
                $urData = array();
                foreach ($user_role_add as $k => $v) {
                    $urData[$k]['role_id'] = $v;
                    $urData[$k]['user_id'] = $id;
                    $urData[$k] = array_merge(array_merge($urData[$k], $info), $infos);
                }
                model('UserRole')->insertAll($urData);
            }else{
                model('UserRole')->where($where)->update(array_merge($infos, $rData));
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
    public function delete($id){
        $validate = new UserValidate();
        $result = $validate->scene('delete')->check($id);
        if(!$result){
            exception($validate->getError());
        }
        $adminName = (new Session())->get('USER_INFO.userName');
        $data = [];
        $data['updater'] = $adminName;
        $data['update_time'] = time();
        $data['is_delete'] = 1;
        return model("User")->save($data, ['id' => $id]);
    }

}